package top.fzqblog.kotlinapp.http

import android.content.Context
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.CookieJar
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import top.fzqblog.kotlinapp.util.ApiContants

/**
 * Created by 抽离 on 2017/11/16 0016.
 */
class ApiRetrofit(val context: Context) {

    var retrofit: Retrofit? = null

    private fun getClient():OkHttpClient{
        val builder = OkHttpClient.Builder()
        val cookieJar: CookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(context));
        val okHttpClient = builder
                .addNetworkInterceptor(
                        HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .cookieJar(cookieJar)
//                .addInterceptor(ReceivedCookiesInterceptor(context))
//                .addInterceptor(AddCookiesInterceptor(context))
                .build()
        return okHttpClient
    }

    init {
        retrofit = Retrofit.Builder()
                .baseUrl(ApiContants.BASE_URL)
                .client(getClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
    }

    companion object {
        var instance: ApiRetrofit? = null

        fun getInstance(context: Context): ApiRetrofit{
            if (instance == null){
                synchronized(ApiRetrofit::class){
                    if(instance == null){
                        instance = ApiRetrofit(context)
                    }
                }
            }
            return instance !!
        }
    }

    fun <T> create(service: Class<T>?): T? {
        if (service == null) {
            throw RuntimeException("Api service is null!")
        }
        return retrofit?.create(service)
    }

}